const api = require('../../utils/api')
const util = require('../../utils/util')

Page({
  data: {
    reminders: [],
    filteredReminders: [],
    currentTab: 'all',
    stats: {
      total: 0,
      completed: 0,
      active: 0,
      highPriority: 0,
      completionRate: 0,
      typeDistribution: []
    },
    showMenu: false,
    currentReminderId: null
  },

  onLoad() {
    this.loadReminders()
  },

  onShow() {
    this.loadReminders()
  },

  // 加载所有提醒
  async loadReminders() {
    try {
      wx.showLoading({ title: '加载中...' })
      
      // 获取提醒列表
      const result = await api.reminder.getReminders()
      
      if (result && result.success && result.data) {
        // 处理提醒数据，添加展示用字段
        const reminders = result.data.map(item => this.formatReminderItem(item))
        
        // 按照优先级和时间排序
        reminders.sort((a, b) => {
          // 优先按照优先级排序
          if (a.priority !== b.priority) {
            return b.priority - a.priority // 高优先级在前
          }
          
          // 其次按照时间排序
          const timeA = a.hour * 60 + a.minute
          const timeB = b.hour * 60 + b.minute
          return timeA - timeB
        })
        
        this.setData({ 
          reminders: reminders,
          filteredReminders: reminders
        })
        
        // 计算统计数据
        this.calculateStats(reminders)
      } else {
        this.setData({ 
          reminders: [],
          filteredReminders: []
        })
      }
      
      wx.hideLoading()
    } catch (err) {
      console.error('获取提醒列表失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '获取提醒失败',
        icon: 'none'
      })
    }
  },
  
  // 格式化单个提醒项
  formatReminderItem(item) {
    // 格式化时间显示
    const timeDisplay = util.formatHourMinute(item.hour, item.minute)
    
    // 解析重复频率文本
    const repeatText = this.generateRepeatText(item.repeatDays)
    
    // 优先级文本和样式
    const priorityMap = {
      3: { text: '高优先级', class: 'high' },
      2: { text: '中优先级', class: 'medium' },
      1: { text: '低优先级', class: 'low' }
    }
    
    const priority = priorityMap[item.priority] || { text: '普通', class: 'medium' }
    
    // 提醒类型文本
    const typeMap = {
      'medication': '药物提醒',
      'measurement': '测量提醒',
      'exercise': '运动提醒',
      'water': '饮水提醒',
      'assessment': '评估提醒'
    }
    
    return {
      ...item,
      timeDisplay,
      repeatText,
      priorityText: priority.text,
      priorityClass: priority.class,
      typeText: typeMap[item.type] || '其他提醒'
    }
  },
  
  // 生成重复频率文本
  generateRepeatText(repeatDays) {
    if (!repeatDays || repeatDays.length === 0) {
      return '不重复'
    }
    
    if (repeatDays.length === 7) {
      return '每天'
    }
    
    // 检查是否是工作日
    const isWeekdays = repeatDays.length === 5 && 
                     repeatDays.includes(1) && 
                     repeatDays.includes(2) && 
                     repeatDays.includes(3) && 
                     repeatDays.includes(4) && 
                     repeatDays.includes(5)
    
    if (isWeekdays) {
      return '工作日'
    }
    
    // 检查是否是周末
    const isWeekend = repeatDays.length === 2 && 
                     repeatDays.includes(0) && 
                     repeatDays.includes(6)
    
    if (isWeekend) {
      return '周末'
    }
    
    // 自定义组合
    const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const dayTexts = repeatDays.map(day => dayNames[day]).join('、')
    
    return dayTexts
  },
  
  // 计算统计数据
  calculateStats(reminders) {
    if (!reminders || reminders.length === 0) {
      this.setData({
        stats: {
          total: 0,
          completed: 0,
          active: 0,
          highPriority: 0,
          completionRate: 0,
          typeDistribution: []
        }
      })
      return
    }
    
    // 计算各项统计
    const total = reminders.length
    const completed = reminders.filter(item => item.isCompleted).length
    const active = reminders.filter(item => item.enabled && !item.isCompleted).length
    const highPriority = reminders.filter(item => item.priority === 3 && !item.isCompleted).length
    
    // 计算完成率
    const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0
    
    // 计算类型分布
    const typeCount = {}
    const typeNames = {
      'medication': '用药提醒',
      'measurement': '测量提醒',
      'exercise': '运动提醒',
      'water': '饮水提醒',
      'assessment': '评估提醒'
    }
    
    reminders.forEach(item => {
      if (!typeCount[item.type]) {
        typeCount[item.type] = 0
      }
      typeCount[item.type]++
    })
    
    const typeDistribution = Object.keys(typeCount).map(type => {
      const count = typeCount[type]
      const percentage = Math.round((count / total) * 100)
      
      return {
        type,
        name: typeNames[type] || '其他提醒',
        count,
        percentage
      }
    })
    
    // 按数量排序
    typeDistribution.sort((a, b) => b.count - a.count)
    
    this.setData({
      stats: {
        total,
        completed,
        active,
        highPriority,
        completionRate,
        typeDistribution
      }
    })
  },
  
  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ currentTab: tab })
    this.filterReminders(tab)
  },
  
  filterReminders(tab) {
    const { reminders } = this.data
    
    switch (tab) {
      case 'all':
        this.setData({ filteredReminders: reminders })
        break
      case 'today':
        // 获取今天星期几
        const today = new Date().getDay()
        this.setData({ 
          filteredReminders: reminders.filter(item => {
            return !item.repeatDays || item.repeatDays.length === 0 || item.repeatDays.includes(today)
          })
        })
        break
      case 'upcoming':
        this.setData({ 
          filteredReminders: reminders.filter(item => !item.isCompleted)
        })
        break
      case 'completed':
        this.setData({ 
          filteredReminders: reminders.filter(item => item.isCompleted)
        })
        break
      case 'stats':
        // 统计标签页不需要过滤提醒列表，可以置空或保持原样
        this.setData({ 
          filteredReminders: [] 
        })
        break
      default:
        this.setData({ filteredReminders: reminders })
    }
  },
  
  // 添加新提醒
  addNewReminder() {
    wx.navigateTo({
      url: '/pages/reminderEdit/reminderEdit'
    })
  },

  // 编辑提醒
  editReminder(e) {
    const { id } = e.currentTarget.dataset
    
    wx.navigateTo({
      url: `/pages/reminderEdit/reminderEdit?id=${id}`
    })
  },

  // 开关提醒状态
  async toggleReminder(e) {
    const { id } = e.currentTarget.dataset
    
    // 验证ID是否有效
    if (!id) {
      console.error('切换提醒状态失败: ID未定义')
      wx.showToast({
        title: '操作失败: ID无效',
        icon: 'none'
      })
      return
    }
    
    const enabled = e.detail.value
    
    try {
      await api.reminder.updateReminder(id, { enabled })
      
      // 更新本地状态
      const reminders = this.data.reminders.map(item => {
        if (item.id === id) {
          return { ...item, enabled }
        }
        return item
      })
      
      this.setData({ 
        reminders,
        filteredReminders: this.data.filteredReminders.map(item => {
          if (item.id === id) {
            return { ...item, enabled }
          }
          return item
        })
      })
      
      wx.showToast({
        title: enabled ? '提醒已启用' : '提醒已停用',
        icon: 'success'
      })
    } catch (err) {
      console.error('更新提醒状态失败:', err)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },
  
  // 标记提醒为已完成
  async completeReminder(e) {
    const { id } = e.currentTarget.dataset
    
    // 验证ID是否有效
    if (!id) {
      console.error('标记提醒完成失败: ID未定义')
      wx.showToast({
        title: '操作失败: ID无效',
        icon: 'none'
      })
      return
    }
    
    try {
      await api.reminder.completeReminder(id, {
        completedAt: new Date().toISOString()
      })
      
      // 更新本地状态
      const reminders = this.data.reminders.map(item => {
        if (item.id === id) {
          return { ...item, isCompleted: true }
        }
        return item
      })
      
      this.setData({ 
        reminders,
        filteredReminders: this.data.filteredReminders.map(item => {
          if (item.id === id) {
            return { ...item, isCompleted: true }
          }
          return item
        })
      })
      
      // 刷新统计
      this.calculateStats(reminders)
      
      wx.showToast({
        title: '标记完成',
        icon: 'success'
      })
    } catch (err) {
      console.error('标记提醒完成失败:', err)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },
  
  // 显示操作菜单
  showActionMenu(e) {
    const { id } = e.currentTarget.dataset
    
    this.setData({
      showMenu: true,
      currentReminderId: id
    })
  },
  
  // 隐藏操作菜单
  hideActionMenu() {
    this.setData({
      showMenu: false,
      currentReminderId: null
    })
  },
  
  // 从菜单编辑提醒
  editReminderFromMenu() {
    const { currentReminderId } = this.data
    
    this.hideActionMenu()
    
    if (currentReminderId) {
      wx.navigateTo({
        url: `/pages/reminderEdit/reminderEdit?id=${currentReminderId}`
      })
    }
  },
  
  // 从菜单标记提醒完成
  async completeReminderFromMenu() {
    const { currentReminderId } = this.data
    
    this.hideActionMenu()
    
    if (currentReminderId) {
      try {
        await api.reminder.completeReminder(currentReminderId, {
          completedAt: new Date().toISOString()
        })
        
        // 更新本地状态
        const reminders = this.data.reminders.map(item => {
          if (item.id === currentReminderId) {
            return { ...item, isCompleted: true }
          }
          return item
        })
        
        this.setData({ 
          reminders,
          filteredReminders: this.data.filteredReminders.map(item => {
            if (item.id === currentReminderId) {
              return { ...item, isCompleted: true }
            }
            return item
          })
        })
        
        // 刷新统计
        this.calculateStats(reminders)
        
        wx.showToast({
          title: '标记完成',
          icon: 'success'
        })
      } catch (err) {
        console.error('标记提醒完成失败:', err)
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    }
  },
  
  // 延迟提醒
  snoozeReminder() {
    const { currentReminderId } = this.data
    
    this.hideActionMenu()
    
    if (currentReminderId) {
      wx.showActionSheet({
        itemList: ['延迟10分钟', '延迟30分钟', '延迟1小时', '延迟今天'],
        success: async (res) => {
          try {
            let delayMinutes = 0
            
            switch (res.tapIndex) {
              case 0:
                delayMinutes = 10
                break
              case 1:
                delayMinutes = 30
                break
              case 2:
                delayMinutes = 60
                break
              case 3:
                // 延迟到明天同一时间
                delayMinutes = 24 * 60
                break
            }
            
            if (delayMinutes > 0) {
              await api.reminder.snoozeReminder(currentReminderId, {
                delayMinutes
              })
              
              wx.showToast({
                title: '已延迟提醒',
                icon: 'success'
              })
            }
          } catch (err) {
            console.error('延迟提醒失败:', err)
            wx.showToast({
              title: '操作失败',
              icon: 'none'
            })
          }
        }
      })
    }
  },
  
  // 从菜单删除提醒
  deleteReminderFromMenu() {
    const { currentReminderId } = this.data
    
    this.hideActionMenu()
    
    if (currentReminderId) {
      this.deleteReminder({ currentTarget: { dataset: { id: currentReminderId } } })
    }
  },

  // 删除提醒
  deleteReminder(e) {
    const { id } = e.currentTarget.dataset
    
    wx.showModal({
      title: '删除提醒',
      content: '确定要删除这条提醒吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await api.reminder.deleteReminder(id)
            
            // 从列表中移除
            const reminders = this.data.reminders.filter(item => item.id !== id)
            const filteredReminders = this.data.filteredReminders.filter(item => item.id !== id)
            
            this.setData({ 
              reminders,
              filteredReminders
            })
            
            // 刷新统计
            this.calculateStats(reminders)
            
            wx.showToast({
              title: '提醒已删除',
              icon: 'success'
            })
          } catch (err) {
            console.error('删除提醒失败:', err)
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  }
}) 